import { View } from '@tarojs/components';
import Taro, { useDidShow, useRouter } from '@tarojs/taro';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { connect } from 'react-redux';
import Cart from '../standardCartPage/index';
import HomePage from '../standardHomePage/homePage';
import Industry from '../standardIndustry/index';
import TabsMenu from '../tabsMenu/index';
import './index.scss';

const TabsPage = ({ dispatch, tabsPageName = 'homePage', config = {} }) => {
  const { params: { tabName } = {} } = useRouter();
  // 如果路由中存在 tabName, 使用路由名, 否则使用 redux 中数据
  const renderPageNameRef = useRef(tabName ?? tabsPageName);

  const [page, setPage] = useState(renderPageNameRef.current);

  // 当点击底部按钮时, 记录点击的 name
  const updatePage = (name) => {
    renderPageNameRef.current = name;
    setPage(name);
  };

  Taro.useShareAppMessage(() => {
    const pageShareInfo = config?.pageShareInfo;
    return {
      title: pageShareInfo?.shareTitle,
      path: '/pages/mainPages/tabsPage/index',
    };
  });

  useDidShow(() => {
    Taro.$setTabbarList()
    updatePage(renderPageNameRef.current);
  });

  useEffect(() => {
    if (renderPageNameRef.current != page) {
      dispatch({
        type: 'otherApi/setTabsPageName',
        payload: page,
      });
    }
  }, [page, renderPageNameRef]);

  const pageEle = useMemo(() => {
    console.log('debug for render menu', { page });
    let tabIdx = 0;
    let content = null;

    switch (page) {
      case 'homePage':
        tabIdx = 0;
        content = <HomePage />;
        break;
      // case 'industry':
      //   tabIdx = 1;
      //   content = <Industry />;
      //   break;
      case 'cart':
        tabIdx = 1;
        content = <Cart />;
        break;
      // case 'me':
      //   tabIdx = 2;
      //   content = <Me />;
      //   break;
      default:
        break;
    }
    return (
      <>
        {content}
      </>
    );
  }, [page]);

  return <View className="menuPages">{pageEle}</View>;
};

export default connect(({ otherApi }) => ({
  tabsPageName: otherApi.tabsPageName,
  config: otherApi.customPageConfigPages?.home,
}))(TabsPage);
